import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
} from '@nestjs/common';
import { MadeService } from './made.service';
import { CreateMbillDto } from './dto/create-mbilling.dto';

@Controller('made')
export class MadeController {
  constructor(private readonly madeService: MadeService) {}

  @Post('generate')
  async generateImage(@Body('data') data: object) {
    try {
      console.log(data);
      const info = await this.madeService.generateImage(data);
      return info;
    } catch (error) {
      return { error: 'Failed to generate image', message: error.message };
    }
  }

  @Post('searchproduct')
  searchproduct(@Body('keyword') keyword: string) {
    return this.madeService.searchProductByKeyword(keyword);
  }

  @Post('searchcustomer')
  searchcustomer(@Body('keyword') keyword: string) {
    return this.madeService.searchCustomerByKeyword(keyword);
  }

  @Post('saveorder')
  create(@Body() createMbillDto: CreateMbillDto) {
    return this.madeService.createOrder(createMbillDto);
  }

  @Get()
  findAll() {
    return this.madeService.findAll();
  }

  @Get('search')
  searchGet(
    @Query('keyword') keyword: string,
    @Query('page') page?: string,
    @Query('limit') limit?: string,
  ) {
    const pageNum = page ? Math.max(1, parseInt(page, 10) || 1) : 1;
    const pageSize = limit
      ? Math.max(1, Math.min(parseInt(limit, 10) || 50, 1000))
      : 50;

    return this.madeService.searchByKeyword(keyword || '', pageNum, pageSize);
  }

  @Get('order/:orderNumber')
  findByOrderNumber(@Param('orderNumber') orderNumber: string) {
    return this.madeService.findOne(orderNumber);
  }

  @Get(':orderNumber')
  findOne(@Param('orderNumber') orderNumber: string) {
    return this.madeService.findOne(orderNumber);
  }

  @Patch(':id')
  update(@Param('id') id: string) {
    return this.madeService.update(+id);
  }

  @Delete('order/:orderNumber')
  remove(@Param('orderNumber') orderNumber: string) {
    return this.madeService.removeByOrderNumber(orderNumber);
  }

  @Post('search')
  search(
    @Body('keyword') keyword: string,
    @Body('page') page: number = 1,
    @Body('limit') limit: number = 50,
  ) {
    return this.madeService.searchByKeyword(keyword, page, limit);
  }
}
